package com.chatgpt;

import okhttp3.*;
import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class ChatGPTExample {

    // 模拟“测试区域.txt”中的数据
    private static final Map<String, String> regionMap = new HashMap<>();

    static {
        regionMap.put("徐汇区", "李强，手机号: 18092751093");
        regionMap.put("浦东新区", "王芳，手机号: 13572982439");
        regionMap.put("长宁区", "陈伟，手机号: 18217144395");
        regionMap.put("静安区", "刘婷，手机号: 13031612195");
    }

    public static void main(String[] args) throws IOException {
        String userMessage = "你好，我想在淞沪路这边找一个3000的房子";

        // 尝试匹配区域负责人
        String matchedResponse = matchRegion(userMessage);
        if (matchedResponse != null) {
            System.out.println("匹配结果：" + matchedResponse);
            return;
        }

        // 如果没匹配到，调用 ChatGPT
        String reply = callChatGPT(userMessage);
        System.out.println("ChatGPT 回复：" + reply);
    }

    // 根据关键词匹配区域
    private static String matchRegion(String message) {
        for (Map.Entry<String, String> entry : regionMap.entrySet()) {
            if (message.contains(entry.getKey())) {
                return "您可以联系" + entry.getValue();
            }
        }
        return null;
    }

    // 调用 ChatGPT 接口
    private static String callChatGPT(String message) throws IOException {
        OkHttpClient client = new OkHttpClient();

        MediaType mediaType = MediaType.get("application/json");
        JSONObject json = new JSONObject();
        json.put("model", "gpt-3.5-turbo");

        json.put("messages", new org.json.JSONArray()
                .put(new JSONObject().put("role", "user").put("content", message)));

        RequestBody body = RequestBody.create(json.toString(), mediaType);
        Request request = new Request.Builder()
                .url("https://api.openai.com/v1/chat/completions")
                .post(body)
                .addHeader("Authorization", "Bearer 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")
                .addHeader("Content-Type", "application/json")
                .build();

        Response response = client.newCall(request).execute();
        String result = response.body().string();

        System.out.println(result);
        // 提取返回文本
//        JSONObject resJson = new JSONObject(result);
//        return resJson.getJSONArray("choices")
//                .getJSONObject(0)
//                .getJSONObject("message")
//                .getString("content");
        return result;
    }
}
